package br.com.uniti.academico.persistence.manager.aluno.impl;

import br.com.uniti.academico.persistence.entity.Aluno;
import br.com.uniti.academico.persistence.manager.aluno.AlunoManager;
import com.google.code.liquidform.LiquidForm;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;

public class AlunoManagerImpl implements AlunoManager {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @Transactional
    public Aluno salvar(Aluno aluno) {

        if (aluno.getRa() == null) {
            throw new IllegalArgumentException("Aluno com ra nulo;");
        }

        if (existeAlunoComRa(aluno.getRa())) {
            throw new IllegalArgumentException("Aluno com ra repetido.");
        }

        entityManager.persist(aluno);
        return aluno;
    }

    private boolean existeAlunoComRa(String ra) {
        Aluno a = LiquidForm.alias(Aluno.class, "a");
        String sql = LiquidForm.select(a).from(Aluno.class).as(a).where(
                LiquidForm.eq(a.getRa(), ra)).toString();

        System.out.println("SQL : " + sql);

        try {
            Aluno aluno = (Aluno) entityManager.createQuery(sql).getSingleResult();
            if (aluno != null) {
                return true;
            } else {
                return false;
            }
        } catch (NoResultException e) {
            return false;
        }
    }

}
